﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

using SBPweb.RIA.Client.Contracts.Base;
using SBPweb.RIA.Client.Controls.Base;

using SBPweb.PlAzureNet.Client.Library;
using SBPweb.PlAzureNet.Client.Library.Social;
using SBPweb.PlAzureNet.Client.Library.Social.Actors;

using SBPweb.PlAzureNet.Client.Modules.Facebook.API;

namespace SBPweb.PlAzureNet.Client.Modules.Facebook.Controls
{

    public partial class Friends : UserControl
    {

        public Friends()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Friends_Loaded);

            if (ExtendableApplication.Current != null && !ExtendableApplication.Current.IsDesignTime)
            {
                icFriends.ItemsSource = Connector.Instance.Friends;

                Connector.Instance.Friends.Fetching += new EventHandler(Friends_Fetching);
                Connector.Instance.Friends.Fetched += new EventHandler(Friends_Fetched);
            }
        }

        private void Friends_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void Friends_Fetching(object sender, EventArgs e)
        {
        }

        private void Friends_Fetched(object sender, EventArgs e)
        {
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            Image img = sender as Image;
            IUser iu = img.DataContext as IUser;
            SetFallbackImage(img, iu);
        }

        private void Image_Loaded(object sender, RoutedEventArgs e)
        {
            Image img = sender as Image;
            IUser iu = img.DataContext as IUser;
            if (iu.AvatarUri.LocalPath.EndsWith(".gif"))
            {
                SetFallbackImage(img, iu);
            }
            else
            {
                img.Source = new BitmapImage(iu.AvatarUri);
            }
        }

        private static void SetFallbackImage(Image img, IUser iu)
        {
            img.Source = typeof(User).GetEmbeddedBitmapImage(string.Format("Resources.User_{0}_100x100.png", iu.Gender.ToString()));
        }
        
    }

}